package captcha.controller;

import captcha.model.CaptchaPropertities;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {

    @Autowired
    private CaptchaPropertities captchaPropertities;

    private final static Long VALID_TIME = 30 * 60 * 1000L;

    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session){
        Long start = System.currentTimeMillis();
        response.setContentType("image/jpg");
        //一般前端处理
        response.setHeader("Progma", "No-cache");
        response.setCharacterEncoding("utf-8");
        //生成验证码
        try {
            ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(captchaPropertities.getWidth(), captchaPropertities.getHeight());
            String code = captcha.getCode();
            session.setAttribute(captchaPropertities.getSession().getKey(), code);
            session.setAttribute(captchaPropertities.getSession().getDate(), new Date());

            captcha.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("cost time:" + (end - start) + "ms");
//        }finally {
//            response.getOutputStream().close();
//        }
    }

    /**
     * 验证用户输入的验证码是否正确
     * @param captcha: 用户输入的验证码
     * @param session
     * @return false: 校验失败, true: 成功
     */

    @RequestMapping("/check")
    public boolean check(String captcha,HttpSession session){
        if(!StringUtils.hasLength(captcha)){
            return false;
        }

        String code = (String) session.getAttribute(captchaPropertities.getSession().getKey());
        Date date = (Date) session.getAttribute(captchaPropertities.getSession().getDate());
        //验证码正确且没有过期
        if(captcha.equalsIgnoreCase(code) && date != null && System.currentTimeMillis() - date.getTime() < VALID_TIME){
            return true;
        }
        return false;
    }
}
